package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.CertifiedOwnerApplyDao;
import com.cci.kangdao.dao.CertifiedOwnerApplyRecordDao;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.dao.model.CertifiedOwnerApplyRecordT;
import com.cci.kangdao.dao.model.CertifiedOwnerApplyT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.request.CertifiedOwnerApplyRequest;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CertifiedOwnerApplyService;
import com.cci.kangdao.utilTool.*;
import com.gexin.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @author linjiankun
 * @date 2023/03/06 9:46
 */
@Service("CertifiedOwnerApplyService")
public class CertifiedOwnerApplyServiceImpl implements CertifiedOwnerApplyService {

    private Logger log = Logger.getLogger(this.getClass().getName());
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Autowired
    private CertifiedOwnerApplyDao certifiedOwnerApplyDao;
    @Autowired
    private CertifiedOwnerApplyRecordDao certifiedOwnerApplyRecordDao;
    @Autowired
    private CustomerEngineRelDao customerEngineRelDao;

    @Override
    @Transactional
    public ModelAndView submitCertifiedOwnerApply(String paramStr, HttpServletRequest request,
                                                   HttpServletResponse response){
        log.info("submitCertifiedOwnerApply.aspx接口入参paramStr："+paramStr);
        JSONObject obj = new JSONObject();
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        //响应的data数据
        Map<String,Object> returnMap = new HashMap<>();
        //1.提取参数信息
        CertifiedOwnerApplyRequest certifiedOwnerApplyRequest = JSON.parseObject(paramStr, CertifiedOwnerApplyRequest.class);
        //2.校验参数是否必填
        Long customerEngineRelId =certifiedOwnerApplyRequest.getCustomerEngineRelId();
        String buyCarContractUrl =certifiedOwnerApplyRequest.getBuyCarContractUrl();
        String buyCarInvoiceUrl =certifiedOwnerApplyRequest.getBuyCarInvoiceUrl();
        String engineNameplateUrl =certifiedOwnerApplyRequest.getEngineNameplateUrl();
        if(null == userT || customerEngineRelId == -1 || StringUtils.isEmpty(buyCarContractUrl) || StringUtils.isEmpty(buyCarInvoiceUrl)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数或所传参数非枚举值！");
            return null;
        }
        // 加锁处理，避免发生多次提交。
        String lockKey= "submitCertifiedOwnerApply-" + userT.getId();
        if (!redisClientUtils.lock(lockKey, 60L)) {
            //防止并发
            ParameterTool.writeErrorResponse(response, -98);
            return null;
        }
        try {
            CertifiedOwnerApplyT certifiedOwnerApplyT = new CertifiedOwnerApplyT();
            certifiedOwnerApplyT.setCustomerEngineRelId(customerEngineRelId);
            certifiedOwnerApplyT.setCertifiedStatus(0);
            certifiedOwnerApplyT.setBuyCarContractUrl(buyCarContractUrl);
            certifiedOwnerApplyT.setBuyCarInvoiceUrl(buyCarInvoiceUrl);
            certifiedOwnerApplyT.setEngineNameplateUrl(engineNameplateUrl);
            certifiedOwnerApplyT.setCreator(userT.getId());
            certifiedOwnerApplyT.setCreateTime(currentTime);
            int num =  certifiedOwnerApplyDao.insertSelective(certifiedOwnerApplyT);
            if(num > 0){
                CertifiedOwnerApplyRecordT certifiedOwnerApplyRecordT = new CertifiedOwnerApplyRecordT();
                certifiedOwnerApplyRecordT.setCertifiedOwnerApplyId(certifiedOwnerApplyT.getId());
                certifiedOwnerApplyRecordT.setCertifiedStatus(0);
                certifiedOwnerApplyRecordT.setCreator(certifiedOwnerApplyT.getId());
                certifiedOwnerApplyRecordT.setCreateTime(currentTime);
                certifiedOwnerApplyRecordDao.insertSelective(certifiedOwnerApplyRecordT);
                Map<String,Object> updateMap = new HashMap<>();
                updateMap.put("CustomerEngineRelID",customerEngineRelId);
                updateMap.put("CertifiedOwnerApplyId",certifiedOwnerApplyT.getId());
                customerEngineRelDao.newUpdateCustomerEngineRel(updateMap);
            }
            obj.put("data",returnMap);
            obj.put("status", 0);
            obj.put("msg", "success");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
            ParameterTool.writeResponse(response, msg);
        }finally {
            //释放锁
            redisClientUtils.delkey(lockKey);
        }
        ParameterTool.writeResponse(response, obj.toString());
        return null;
    }



}
